package com.sgb.kjwl.view.ui.adapter.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.model.entity.transport.SearchGoodsEntity;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.utils.VehicleConstant;
import com.sgb.kjwl.view.ui.activity.self.logistics.QuotedOwnerActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.QuotedThirdActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.widget.CenteredImageSpan;
import com.sgb.link.utils.LogisticsLogUtils;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.customview.WSTextView;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.adapter.ItemViewHolder;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;

import java.util.List;

public class SearchGoodsInfoAdapter extends BaseRecycleAdapter<SearchGoodsEntity> {
    public SearchGoodsInfoAdapter(Context context, List<SearchGoodsEntity> datas) {
        super(context, R.layout.item_search_goods_info, datas);
    }

    @Override
    public void convert(ItemViewHolder holder, SearchGoodsEntity goodsInfoEntity) {
        holder.setBinding(BR.viewModel, goodsInfoEntity);
        TextView type_name = holder.itemView.findViewById(R.id.type_name);
        TextView price_view = holder.itemView.findViewById(R.id.price_view);
        TextView content_view = holder.itemView.findViewById(R.id.content_view);
        TextView tv_company = holder.itemView.findViewById(R.id.tv_company);
        TextView tv_distance = holder.itemView.findViewById(R.id.tv_distance);
        WSTextView tv_city = holder.itemView.findViewById(R.id.tv_city);
        TextView tv_lowest_price = holder.itemView.findViewById(R.id.tv_lowest_price);
        TextView car_number = holder.itemView.findViewById(R.id.car_number);
        TextView tvjourney = holder.itemView.findViewById(R.id.transport_distance);
        TextView load_time = holder.itemView.findViewById(R.id.load_time);
        TextView role = holder.itemView.findViewById(R.id.role);
        RoundedImageView iv_logo = holder.itemView.findViewById(R.id.iv_logo);

        //整车/零担
        ImageView loadType = holder.itemView.findViewById(R.id.load_type);
        String loadTypeStr = CargoConstant.getTransportTypeStr(goodsInfoEntity.getTransportType());
        StringBuilder typeBuilder = new StringBuilder();
        if (!TextUtils.isEmpty(goodsInfoEntity.getGoodsModeName())) {
            typeBuilder.append(CargoConstant.getLastGoodsTypeName(goodsInfoEntity.getGoodsModeName(), goodsInfoEntity.getSecondGoodsTypeName()) + "/");
        }
        if (!TextUtils.isEmpty(goodsInfoEntity.getWeight())) {
            typeBuilder.append(NumberUtil.trim0(goodsInfoEntity.getWeight()) + "吨");
        }
        if (!TextUtils.isEmpty(goodsInfoEntity.getVolume())) {
            typeBuilder.append("/" + NumberUtil.trim0(goodsInfoEntity.getVolume()) + "方");
        }
        type_name.setText(typeBuilder.toString());

        // 一口价/电议
        if (null != goodsInfoEntity.getFreightType() && goodsInfoEntity.getFreightType() == 1) {
            price_view.setText("运费 电议");
        } else {
            price_view.setText(TextUtils.isEmpty(goodsInfoEntity.getAllFreight()) ? "" : context.getResources().getString(R.string.app_the_freight_combined)+" " + NumberUtil.trim0(goodsInfoEntity.getAllFreight()) + "元");
        }
        String carModelNameStr = TextUtils.isEmpty(goodsInfoEntity.getCarModelName()) ? "" : goodsInfoEntity.getCarModelName().replace(",", "/").trim() + " ";
        String carLenStr = TextUtils.isEmpty(goodsInfoEntity.getCarLenName()) ? "" : goodsInfoEntity.getCarLenName().replace(",", "/").trim() + " ";
        String heightHurdleStr = getValidHeightHurdle(goodsInfoEntity.getHeightHurdle()).replace(",", "/").trim() + " ";
        String dumpStr = TextUtils.isEmpty(VehicleConstant.getIsDumpStr(goodsInfoEntity.getIsDump())) ? "" : VehicleConstant.getIsDumpStr(goodsInfoEntity.getIsDump());
        String carInfo = carModelNameStr + carLenStr + heightHurdleStr + dumpStr;
        content_view.setText(StringUtil.removeChar(carInfo, "/"));
    /*    //装货时间调整
        StringBuilder loadTime = new StringBuilder();
        if (goodsInfoEntity.getShipmentTime() > 0) {
            loadTime.append(CargoConstant.stampFormatLoadText(goodsInfoEntity.getShipmentTime(), goodsInfoEntity.getStartPointTime()));
            if (goodsInfoEntity.getShipmentEndTime() > 0 && goodsInfoEntity.getShipmentEndTime() != goodsInfoEntity.getShipmentTime()) {
                loadTime.append("-" + CargoConstant.stampFormatLoadText(goodsInfoEntity.getShipmentEndTime(), goodsInfoEntity.getEndPointTime()));
            }
        } else if (goodsInfoEntity.getShipmentEndTime() > 0) {
            loadTime.append(CargoConstant.stampFormatLoadText(goodsInfoEntity.getShipmentEndTime(), goodsInfoEntity.getEndPointTime()));
        }
        if (loadTime.toString().length() > 0) {
            load_time.setVisibility(View.VISIBLE);
            load_time.setText(loadTime.append(" 装货").toString());
        } else {
            load_time.setVisibility(View.GONE);
        }*/
        //装货时间调整
        String loadTime = CargoConstant.stampFormatListLoadTime(
                goodsInfoEntity.getShipmentTime(), goodsInfoEntity.getStartPointTime(),
                goodsInfoEntity.getShipmentEndTime(), goodsInfoEntity.getEndPointTime());
        if (!TextUtils.isEmpty(loadTime)) {
            load_time.setText(loadTime + "装货");
        } else {
            load_time.setVisibility(View.GONE);
        }
/*        if (goodsInfoEntity.getPattern() != null && goodsInfoEntity.getPattern() == 1) {
//            tvjourney.setVisibility(View.GONE);
            loadType.setVisibility(View.GONE);
        } else {*/
            if (loadTypeStr.equals("零担")) {
                loadType.setVisibility(View.VISIBLE);
                loadType.setImageResource(R.drawable.icon_less_than_tag);
            } else if (loadTypeStr.equals("整车")) {
                loadType.setVisibility(View.VISIBLE);
                loadType.setImageResource(R.drawable.icon_carload_tag);
            } else {
                loadType.setVisibility(View.GONE);
            }
       /* }*/
        if (TextUtils.isEmpty(goodsInfoEntity.getJourney())) {
            tvjourney.setText("");
            tvjourney.setVisibility(View.GONE);
        } else {
            String journey = Double.valueOf(goodsInfoEntity.getJourney()) < 1000 ? "1km以内" : StringUtil.fromatUpDistance(goodsInfoEntity.getJourney()) + "km";
            tvjourney.setText("运程: " + journey);
            tvjourney.setVisibility(View.VISIBLE);
        }

        //计算与货源的距离
        if (TextUtils.isEmpty(goodsInfoEntity.getDistance())) {
            tv_distance.setText("");
        } else {
            tv_distance.setText("距您 " + (Double.valueOf(goodsInfoEntity.getDistance()) < 1000 ? "1km以内" : StringUtil.fromatUpDistance(goodsInfoEntity.getDistance()) + "km"));
        }

        StringBuilder routeStr = new StringBuilder();
        if (!TextUtils.isEmpty(goodsInfoEntity.getCityName())) {
            routeStr.append(goodsInfoEntity.getCityName() + " ");
        }
        if (!TextUtils.isEmpty(goodsInfoEntity.getDistrictName())) {
            routeStr.append(goodsInfoEntity.getDistrictName() + " ➞ ");
        } else {
            routeStr.append(goodsInfoEntity.getDistrictName() + " ➞ ");
        }
        if (!TextUtils.isEmpty(goodsInfoEntity.getDestCityName())) {
            routeStr.append(goodsInfoEntity.getDestCityName() + " ");
        }
        if (!TextUtils.isEmpty(goodsInfoEntity.getDestDistrictName())) {
            routeStr.append(goodsInfoEntity.getDestDistrictName());
        }
        routeStr.append("   ");
        if (goodsInfoEntity.getPattern() == 1) {
           // content_view.setText(TextUtils.isEmpty(goodsInfoEntity.getOfferType()) ? "" : goodsInfoEntity.getOfferTypeWorlds() + " 可报价");
            Drawable drawable = context.getResources().getDrawable(R.drawable.icon_jingjia);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            CenteredImageSpan imgSpan = new CenteredImageSpan(drawable);
            SpannableString spannableString = new SpannableString(routeStr.toString());
            spannableString.setSpan(imgSpan, spannableString.length() - 1, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv_city.setText(spannableString);
            /*if (!TextUtils.isEmpty(goodsInfoEntity.getLowestPrice())) {
                tv_lowest_price.setVisibility(View.VISIBLE);
                tv_lowest_price.setText(Html.fromHtml("<font><small>最低报价 </small></font>" + "<font color='#000000'>" + NumberUtil.trim0(goodsInfoEntity.getLowestPrice()) + "元/吨" + "</font>"));
                if (goodsInfoEntity.getIntentionCarNumber() > 0) {
                    car_number.setText(Html.fromHtml("意向车数 " + "<font color='#5792FD'>" + goodsInfoEntity.getIntentionCarNumber() + ">>" + "</font>"));
                    car_number.setVisibility(View.VISIBLE);
                } else {
                    car_number.setVisibility(View.GONE);
                }
            } else {
                tv_lowest_price.setVisibility(View.GONE);
                car_number.setVisibility(View.GONE);
            }*/
        } else
            tv_city.setText(routeStr.toString());

        if (!TextUtils.isEmpty(goodsInfoEntity.getTerminal())) {
            //头像
            if (!TextUtils.isEmpty(goodsInfoEntity.getLogo())) {
                RequestOptions options = new RequestOptions()
                        .dontAnimate()
                        .placeholder(goodsInfoEntity.getTerminal() != null ? goodsInfoEntity.getTerminal().equals("3") ? R.drawable.geren_person_touxiang : goodsInfoEntity.getTerminal().equals("1") ? R.mipmap.goods_list_company_icon : R.drawable.goods_detail_touxiang : R.drawable.goods_detail_touxiang)
                        .error(goodsInfoEntity.getTerminal() != null ? goodsInfoEntity.getTerminal().equals("3") ? R.drawable.geren_person_touxiang : goodsInfoEntity.getTerminal().equals("1") ? R.mipmap.goods_list_company_icon : R.drawable.goods_detail_touxiang : R.drawable.goods_detail_touxiang)
                        .centerCrop();
                Glide.with(context).load(goodsInfoEntity.getLogo()).apply(options).into(iv_logo);
            } else {
                iv_logo.setImageResource(goodsInfoEntity.getTerminal() != null ? goodsInfoEntity.getTerminal().equals("3") ? R.drawable.geren_person_touxiang : goodsInfoEntity.getTerminal().equals("1") ? R.mipmap.goods_list_company_icon : R.drawable.goods_detail_touxiang : R.drawable.goods_detail_touxiang);
            }

            role.setVisibility(View.VISIBLE);
            switch (goodsInfoEntity.getTerminal()) {
                case "1":
                    role.setBackgroundResource(R.drawable.bg_blue_solid_ring);
                    role.setTextColor(Color.parseColor("#5792FD"));
                    role.setText("企业");
                    if (!TextUtils.isEmpty(goodsInfoEntity.getCompanyName()))
                        tv_company.setText(goodsInfoEntity.getCompanyName());
                    iv_logo.setOval(false);
                    iv_logo.setCornerRadius(4);
                    break;
                case "2":
//                    role.setBackgroundResource(R.drawable.bg_green_ring);
//                    role.setText("中介");
//                    role.setTextColor(Color.parseColor("#06C764"));
                    role.setVisibility(View.GONE);
                    if (!TextUtils.isEmpty(goodsInfoEntity.getTeamName())) {
                        tv_company.setText(goodsInfoEntity.getTeamName());
                    } else if (!TextUtils.isEmpty(goodsInfoEntity.getCompanyName()))
                        tv_company.setText(goodsInfoEntity.getCompanyName());
                    iv_logo.setOval(true);
                    break;

                //个人不展示
                case "3":
//                    role.setBackgroundResource(R.drawable.bg_orange_ring);
//                    role.setText("个人");
//                    role.setTextColor(Color.parseColor("#FFC000"));
                    role.setVisibility(View.GONE);
                    if (!TextUtils.isEmpty(goodsInfoEntity.getUsername())) {
                        tv_company.setText(goodsInfoEntity.getUsername());
                    } else if (!TextUtils.isEmpty(goodsInfoEntity.getCompanyName()))
                        tv_company.setText(goodsInfoEntity.getCompanyName());
                    iv_logo.setOval(true);

            }
        } else {
            role.setVisibility(View.GONE);
        }

        holder.itemView.findViewById(R.id.call_phone).setOnClickListener((View.OnClickListener) v -> callPhone(goodsInfoEntity));
        holder.itemView.findViewById(R.id.car_number).setOnClickListener(v -> {
            if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().
                    getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(context);
            } else {
                if (UserOperating.getInstance().isCompany() && UserOperating.getInstance().getTeamOrCompanyNameNo().equals(goodsInfoEntity.getCompanyNo()) && goodsInfoEntity.getTerminal().equals("1")) {
                    //当前是企业并且跟货源发布人一致
                    QuotedOwnerActivity.start(context, goodsInfoEntity.getNo());
                } else if (UserOperating.getInstance().isTeam() && UserOperating.getInstance().getTeamOrCompanyNameNo().equals(goodsInfoEntity.getTeamNo()) && goodsInfoEntity.getTerminal().equals("2")) {
                    //当前是团队并且跟货源发布人一致
                    QuotedOwnerActivity.start(context, goodsInfoEntity.getNo());
                } else if (UserOperating.getInstance().isPersonal() && UserOperating.getInstance().getUserNo().equals(goodsInfoEntity.getUserNo()) && goodsInfoEntity.getTerminal().equals("3")) {
                    //当前是个人并且跟货源发布人一致
                    QuotedOwnerActivity.start(context, goodsInfoEntity.getNo());
                } else {
                    QuotedThirdActivity.start(context, goodsInfoEntity.getNo());
                }
            }
        });
    }

    private void callPhone(SearchGoodsEntity goodsInfoEntity) {
        if (!isLogin()) {
            VerificationCodeLoginActivity.start(context);
            return;
        }
        if (!TextUtils.isEmpty(goodsInfoEntity.getConnectionPhone()))
            showDialog(goodsInfoEntity);
        else
            MToast.showLongToast(context, "无联系方式");
    }

    private String getValidHeightHurdle(String heightHurdle) {
        if (TextUtils.isEmpty(heightHurdle) || heightHurdle.equals("0.0")) {
            return "";
        }
        return " 栏高 " + heightHurdle + "米";
    }

    private boolean isLogin() {
        return !TextUtils.isEmpty(SharedPreferenceUtil.getInstance().
                getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""));
    }


    private void showDialog(SearchGoodsEntity goodsInfoEntity) {
        String phone = goodsInfoEntity.getConnectionPhone();
        new RoundDialog.Builder(context)
                .title("是否拨打电话")
                .content(phone)
                .confirm("拨打")
                .cancelable(false)
                .confirmCallback(v -> {
                    LogisticsLogUtils.getInstance().logisticsFlow("6", "货源联系人", "icon");
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent.setData(data);
                    context.startActivity(intent);
                })
                .show();
    }
}
